package com.itheima.sms.job;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.sms.entity.TimingPushEntity;
import com.itheima.sms.factory.SmsFactory;
import com.itheima.sms.mapper.TimingPushMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 定时发送短信
 */
@Component
@Slf4j
public class SendTimingSmsImpl implements SendTimingSms {

    @Autowired
    private TimingPushMapper timingPushMapper;

    @Autowired
    private SmsFactory smsFactory;


    /**
     * 发送定时短信
     *
     * @param timing 发送时间 格式 yyyy-MM-dd HH:mm
     */
    @Override
    @Async
    public void execute(String timing) {
        // 1.查询DB获取本次要发送的定时短信
        List<TimingPushEntity> timingPushEntityList = timingPushMapper
                .selectList(Wrappers.<TimingPushEntity>lambdaQuery()
                        // 0表示是未处理
                        .eq(TimingPushEntity::getStatus, 0)
                        // 需要进行时间范围判断吗?, SendSmsJob 定时器每分钟执行一次
                        .eq(TimingPushEntity::getTiming, timing)
                        .orderByAsc(TimingPushEntity::getCreateTime));

        if (timingPushEntityList != null && timingPushEntityList.size() > 0) {
            log.info("本次定时任务需要发送的定时短信条数为: {}", timingPushEntityList.size());
            timingPushEntityList.forEach(timingPushEntity -> {
                // 2.调用短信工厂发送短信
                String deserialize = timingPushEntity.getRequest();
                boolean send = smsFactory.send(deserialize);
                // 3.更新短信发送状态为 "已处理" --> 1
                timingPushEntity.setStatus(1);
                timingPushMapper.updateById(timingPushEntity);
            });
        }
    }
}
